package com.sense.kukoo.biz_library.view

import android.text.Html
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.sense.kukoo.biz_library.R
import com.sense.kukoo.biz_library.adapter.HistoryAdapter
import com.sense.kukoo.biz_library.databinding.BizLibraryFragmentHistoryBinding
import com.sense.kukoo.biz_library.vm.HistoryViewModel
import com.sense.kukoo.common.event.MainPageEvent
import com.sense.kukoo.common.mvvm.view.BaseMvvmFragment
import com.sense.kukoo.common.repo.bean.HistoryItemBean
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.common.wiget.dialog.DeleteItemPopupWindow
import com.sense.kukoo.common.wiget.state.EmptyHistoryState
import com.sense.kukoo.lib_logger.LoggerManager
import com.zy.multistatepage.state.SuccessState
import org.greenrobot.eventbus.EventBus

class HistoryFragment : BaseMvvmFragment<HistoryViewModel, BizLibraryFragmentHistoryBinding>() {

    private val TAG: String = javaClass.simpleName
    private val animateDuration = 400L

    private var mAdapter: HistoryAdapter? = null
    private var isEmptyHistory = false
    private var isSelectAll = false

    override fun getLayout(): Int = R.layout.biz_library_fragment_history

    override fun getViewModelClass(): Class<HistoryViewModel> = HistoryViewModel::class.java

    companion object {
        @JvmStatic
        fun newInstance() = HistoryFragment()
    }

    override fun initParam() {}

    override fun responseVM(action: Int) {}

    override fun initData() {
        mBinding.lifecycleOwner = this
        mBinding.vm = mViewModel
        //
        mViewModel.mHistory.observe(viewLifecycleOwner) {
            LoggerManager.d("HistoryFragment mHistory.observe")
            if(it.size == 0){
                isEmptyHistory = true
                multiState.show<EmptyHistoryState> {
                    it.onExplore {
                        EventBus.getDefault().post(MainPageEvent(0))
                    }
                }
            }else{
                isEmptyHistory = false
                multiState.show<SuccessState>()
                //
                mBinding.refreshLayout.finishRefresh()
                mBinding.refreshLayout.finishLoadMore()
                mAdapter?.list = it
                mAdapter?.notifyDataSetChanged()
            }
        }
        mViewModel.enableLoadMore.observe(viewLifecycleOwner) {
            mBinding.refreshLayout.setEnableLoadMore(it)
        }
    }

    override fun initView() {
        mAdapter = HistoryAdapter(mutableListOf(), mEventListener)
        mBinding.recyclerView.adapter = mAdapter

        val linearLayoutManager = LinearLayoutManager(context)
        mBinding.recyclerView.layoutManager = linearLayoutManager
        mBinding.refreshLayout.setOnRefreshListener {
            //OnRefresh
            //mViewModel.initData()
            mBinding.refreshLayout.finishRefresh()
        }
        mBinding.refreshLayout.setOnLoadMoreListener {
            //OnLoadMore
            //mViewModel.getMoreData()
            mBinding.refreshLayout.finishLoadMore()
        }
        mBinding.llBtnSelectAll.setOnClickListener {
            mAdapter?.let {
                toggleSelectAll()
            }
        }
        mBinding.tvBtnDelete.setOnClickListener {
            //删除多个
            mAdapter?.let {
                val list = it.list
                val deletes = arrayListOf<HistoryItemBean>()
                for (i in list) {
                    if (i.isChecked) {
                        deletes.add(i)
                    }
                }
                mViewModel.setDeleteItem(deletes)
            }
        }
    }

    override fun singleLazyLoad() {}

    override fun onResume() {
        super.onResume()
        refresh()
    }

    fun refresh(){
        LoggerManager.d("HistoryFragment refresh()")
        mBinding.refreshLayout.autoRefresh()
    }

    val mEventListener = object : HistoryAdapter.HistoryEventListener {
        override fun onItemClick(itemView: View, bean: HistoryItemBean) {
            /*//直接进入播放页，根据上次播放进度继续播放
            val data = LocalMediaListItemBean()
            data.book = bean.item.bookItem
            LoggerManager.e("data.book=${data.book}")
            data.mCoverUrl = bean.item.book.coverUrl
            data.name = bean.item.book.name
            data.isSubscription = bean.item.book.isSubscription
            data.chapterTotal = bean.item.book.chapterTotal
            data.isChapter = bean.item.book.isChapter
            data.type = bean.item.book.type ?: 0
            //播放
            Kukoo.input.play(data)
            //打开播放页
            context?.let {
                ARouter.getInstance()
                    .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_CONTROLER_ACTIVITY)
                    .navigation()
            }*/
        }

        override fun onItemLongClick(itemView: View, bean: HistoryItemBean) {
            //
            val location = IntArray(2)
            itemView.getLocationInWindow(location)
            val locationY = location[1]
            val height = mBinding.refreshLayout.height
            val isUp: Boolean = locationY > height * 0.5
            //
            DeleteItemPopupWindow.create(activity, null)
                .show(itemView, isUp)
                .setListener {
                    //删除一个
                    mViewModel.setDeleteItem(arrayListOf(bean))
                }
        }

        override fun onItemCheckedChanged(itemView: View, bean: HistoryItemBean) {
            var checkedCount = 0
            val isSelsectAllItem:Boolean
            mAdapter?.let {
                val list = it.list
                for (i in list) {
                    if (i.isChecked) {
                        checkedCount++
                    }
                }
                isSelsectAllItem = checkedCount == list.size
                setBtnSelectAllState(isSelsectAllItem)
            }
            setDeleteMsg(checkedCount)
        }
    }

    private fun toggleSelectAll(){
        val newSelectAll = !isSelectAll
        mAdapter?.let {
            val list = it.list
            for (i in list) {
                i.isChecked = newSelectAll
            }
            it.notifyDataSetChanged()
            setDeleteMsg(if(newSelectAll) list.size else 0)
        }
        setBtnSelectAllState(newSelectAll)
    }

    private fun setBtnSelectAllState(isSelectAllItem:Boolean){
        if (isSelectAll!=isSelectAllItem) {
            isSelectAll = isSelectAllItem
            if (isSelectAll) {
                mBinding.ivIsSelectAll.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_edit_select_on)
            }else{
                mBinding.ivIsSelectAll.setImageResource(com.sense.kukoo.common.R.drawable.common_icon_edit_select_off)
            }
        }
    }

    private fun setDeleteMsg(checkedCount:Int){
        val checkedCountStr = "<font color=\"#FF3B30\">${checkedCount}</font>"
        val str = getString(
                com.sense.kukoo.common_i18n.R.string.library_selected_count,
                checkedCountStr
        )
        mBinding.tvDeleteMsg.setText(Html.fromHtml(str))
    }

    fun onEditEvent(isEdit: Boolean) {
        LoggerManager.d(TAG, "onEditEvent() isEdit=" + isEdit)
        mAdapter?.isEditMode = isEdit
        if (isEdit) {
            mBinding.refreshLayout.setEnableRefresh(false)
            mBinding.refreshLayout.setEnableLoadMore(false)
        } else {
            mBinding.refreshLayout.setEnableRefresh(true)
            mBinding.refreshLayout.setEnableLoadMore(mViewModel.enableLoadMore.value ?: true)
        }
        showBottom(isEdit)
    }

    private fun showBottom(isShow: Boolean) {
        if (isShow) {
            mBinding.bgIsSelected.visibility = View.VISIBLE
            setBtnSelectAllState(false)
            setDeleteMsg(0)
            //动画
            var height: Float = 0f + mBinding.bgIsSelected.height
            if (height <= 0) {
                height += ApplicationContext.dp2px(49f)
            }
            mBinding.bgIsSelected.translationY = height
            mBinding.bgIsSelected.animate().translationY(0f).setDuration(animateDuration).start()

        } else {
            //动画
            val height = 0f + mBinding.bgIsSelected.height
            mBinding.bgIsSelected.animate()
                .translationY(height)
                .setDuration(animateDuration)
                .withEndAction {
                    mBinding.bgIsSelected.visibility = View.GONE
                }
                .start()
        }
    }
}